package org.ljy.springblog.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.websocket.Session;
import org.ljy.springblog.enums.ResultCodeEnum;
import org.ljy.springblog.model.BlogInfo;
import org.ljy.springblog.model.Result;
import org.ljy.springblog.model.UserInfo;
import org.ljy.springblog.service.BlogService;
import org.ljy.springblog.service.UserService;
import org.ljy.springblog.utils.JwtUtils;
import org.ljy.springblog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {


    @Autowired
    private UserService userService;





    //@Autowired
//    public UserController(UserService userService) {
//        this.userService = userService;
//    }

    /**
     * 用户登陆
     */
    @RequestMapping("/login")
    public Result login(String userName, String password) {
        //1.验证账号密码合法性
        if(!StringUtils.hasLength(userName) && !StringUtils.hasLength(password)) {
            return Result.fail(ResultCodeEnum.FAIL.getCode(),"账目密码不能为空");
        }
        //2.根据用户名获取用户信息
        UserInfo userInfo = userService.getUserInfoByName(userName);
        //3.判断用户是否存在
        if(userInfo == null || userInfo.getId()<0) {
            return Result.fail(ResultCodeEnum.FAIL.getCode(),"用户不合法");
        }
        //4.判断密码正确性
        if(!SecurityUtils.decode(password,userInfo.getPassword())) {

            return Result.fail(ResultCodeEnum.PARAM_ERROR.getCode(), "密码错误");
        }

//        if(!password.equals(userInfo.getPassword())) {
//            return Result.fail(ResultCodeEnum.PARAM_ERROR.getCode(), "密码错误");
//        }
        //5.账目密码正确，开始发放令牌（token）
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id", userInfo.getId());
        cliams.put("name", userInfo.getUserName());
        //6.返回令牌字符串
        String jwt = JwtUtils.genJwt(cliams);
        return Result.success(jwt);
    }






    /**
     *  在博客列表页，获取当前登陆用户的用户信息
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        //1.获取token
        String token = request.getHeader("user_token_header");
        //2.获取id
        Integer userId = JwtUtils.getUserIdByToken(token);
        Assert.notNull(userId,"用户未登录");
        return userService.getUserInfoById(userId);
    }

    /**
     * 在博客详情页，获取当前文章作者的用户信息
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        Assert.notNull(blogId,"blogId不能为null");
        return userService.getUserInfoByBlogId(blogId);
    }








}
